package org.jiucheng.magpiebridge.server.aio.proxy;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.CompletionHandler;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.jiucheng.magpiebridge.protocol.Message;
import org.jiucheng.magpiebridge.server.aio.ServerWriteCompletionHandler;
import org.jiucheng.magpiebridge.server.aio.ServerWriteNoProxyClientReadCompletionHandler;

/**
 * 
 * @author jiucheng
 *
 */
public class ProxyReadCompletionHandler implements CompletionHandler<Integer, ProxyAttachment> {
    
    private static final Logger LOGGER = Logger.getLogger(ProxyReadCompletionHandler.class.getName());
    
    public void completed(Integer result, ProxyAttachment attachment) {
        if (result == -1) {
            try {
                attachment.getAsynchronousSocketChannel().close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            Message proxym = new Message();
            proxym.setMagic(Message.MAGIC);
            proxym.setType(Message.Type.DISCONNECT);
            proxym.setUri(attachment.getUri());
            ByteBuffer writeBuffer = Message.toByteBuffer(proxym);
            if (attachment.getServerAttachment().canWrited()) {
                attachment.getServerAttachment().getServer().write(writeBuffer, attachment.getServerAttachment().setWriteBuffer(writeBuffer), new ServerWriteNoProxyClientReadCompletionHandler());
                return;
            }
        }
        
        ByteBuffer readByteBuffer = attachment.getReadBuffer();
        readByteBuffer.flip();
        Message message = new Message();
        message.setMagic(Message.MAGIC);
        message.setType(Message.Type.TRANSFER);
        message.setUri(attachment.getUri());
        byte[] bts = new byte[result];
        readByteBuffer.get(bts);
        message.setData(bts);
        message.setSize(bts.length);
        ByteBuffer writeBuffer = Message.toByteBuffer(message);
        if (attachment.getServerAttachment().canWrited()) {
        	attachment.getServerAttachment().getServer().write(writeBuffer, attachment.getServerAttachment().setWriteBuffer(writeBuffer), new ServerWriteCompletionHandler());
        }
    }
    
    public void failed(Throwable exc, ProxyAttachment attachment) {
        if (LOGGER.isLoggable(Level.FINE)) {
            LOGGER.log(Level.FINE, "", exc);
        }
        Message proxym = new Message();
        proxym.setMagic(Message.MAGIC);
        proxym.setType(Message.Type.DISCONNECT);
        proxym.setUri(attachment.getUri());
        ByteBuffer writeBuffer = Message.toByteBuffer(proxym);
        if (attachment.getServerAttachment().canWrited()) {
            attachment.getServerAttachment().getServer().write(writeBuffer, attachment.getServerAttachment().setWriteBuffer(writeBuffer), new ServerWriteNoProxyClientReadCompletionHandler());
        }
        // exc.printStackTrace();
    }
}
